package com.chmingx.JavaBasic.re;

import java.util.regex.*;

public class RegexUtils {

    public static void phone(String s) {
        String re = "0\\d{2}-\\d{8}|0\\d{3}-d{7}";
        if (s.matches(re)) {
            System.out.println("success");
        } else {
            System.out.println("failure");
        }
    }

    public static boolean email(String s) {
        String re = "^[a-zA-Z]\\w{5,}@\\w+\\.\\w+";
        return s.matches(re);
    }

    /**
     * 分组匹配
     * @param s a string to be matched
     */
    public static void pattern(String s) {
        Pattern pattern = Pattern.compile("(\\d{3,4})-(\\d{7,8})");
        Matcher matcher = pattern.matcher(s);
        if (matcher.matches()) {
            String group0 = matcher.group(0);
            String group1 = matcher.group(1);
            String group2 = matcher.group(2);
            System.out.println(group0);
            System.out.println(group1);
            System.out.println(group2);
        } else {
            System.out.println("Fail!");
        }
    }

    /**
     * 搜索
     * @param s string
     */
    public static void search(String s) {
        Pattern pattern = Pattern.compile("\\wo\\w");
        Matcher matcher = pattern.matcher(s);
        while (matcher.find()) {
            String sub = s.substring(matcher.start(), matcher.end());
            System.out.println(sub);
        }
    }

    /**
     * 替换
     * @param src string
     */
    public static void replace(String src) {
        String r = src.replaceAll("\\s+", " ");
        System.out.println(r);

        // $1 反向引用匹配到的子串
        String r1 = src.replaceAll("\\s+([a-z]{4})\\s+", " <b>$1</b> ");
        System.out.println(r1);
    }

    /**
     * 拆分
     * @param s string
     */
    public static void split(String s) {
        String[] chars = s.split("[\\,\\;\\s]+");
        for (String s1 :
                chars) {
            System.out.println(s1);
        }

    }

}
